<template>
  <view class="apply-settlement">
    <!-- 订单信息卡片 -->
    <view class="section">
      <view class="section-title">📦 订单信息</view>
      <view class="order-card">
        <view class="info-row">
          <text class="label">订单号</text>
          <text class="value">{{ orderInfo.orderNo }}</text>
        </view>
        <view class="info-row">
          <text class="label">服务类型</text>
          <text class="value">{{ orderInfo.categoryName }}</text>
        </view>
        <view class="info-row">
          <text class="label">完成时间</text>
          <text class="value">{{ orderInfo.confirmTime }}</text>
        </view>
      </view>
    </view>

    <!-- 收益明细 -->
    <view class="section">
      <view class="section-title">💰 收益明细</view>
      <view class="earning-card">
        <!-- 正常订单收益 -->
        <template v-if="orderInfo.status !== 8">
          <view class="fee-row">
            <text class="label">订单金额</text>
            <text class="value">¥{{ orderInfo.actualAmount }}</text>
          </view>
          <view class="fee-row deduction">
            <!-- <text class="label">平台服务费({{ (orderInfo.platformFeeRate ).toFixed(0) }}%)</text> -->
            <text class="label">平台服务费</text>
            <text class="value">-¥{{ orderInfo.platformFee }}</text>
          </view>
          <view class="divider"></view>
          <view class="fee-row total">
            <text class="label">我的收益</text>
            <text class="value highlight">¥{{ orderInfo.riderEarning }}</text>
          </view>
        </template>
        
        <!-- 退款补偿收益 -->
        <template v-else>
          <view class="fee-row">
            <text class="label">原订单金额</text>
            <text class="value">¥{{ orderInfo.actualAmount }}</text>
          </view>
          <view class="fee-row refund">
            <text class="label">订单已退款</text>
            <text class="value">-¥{{ orderInfo.refundAmount }}</text>
          </view>
          <view class="fee-row compensation">
            <text class="label">补偿金额</text>
            <text class="value">¥{{ orderInfo.compensationAmount }}</text>
          </view>
          <view class="divider"></view>
          <view class="fee-row total">
            <text class="label">补偿收益</text>
            <text class="value highlight">¥{{ orderInfo.riderEarning }}</text>
          </view>
        </template>
      </view>
      
      <!-- 抽成规则提示 -->
      <view class="rate-tip">
        <view class="tip-icon">📈</view>
        <view class="tip-content">
          <view class="tip-title">提升收益小贴士</view>
          <view class="tip-desc">结单率越高，平台服务费越低！完成更多订单，享受更优惠的费率~</view>
        </view>
      </view>
    </view>

    <!-- 收款信息 -->
    <view class="section">
      <view class="section-title">💳 收款信息</view>
      <view class="form-card">
        <!-- 收款方式 -->
        <view class="form-item">
          <text class="item-label">收款方式</text>
          <picker @change="onPaymentMethodChange" :value="paymentMethodIndex" :range="paymentMethods">
            <view class="picker">
              <text>{{ paymentMethods[paymentMethodIndex] }}</text>
              <text class="arrow">›</text>
            </view>
          </picker>
        </view>

        <!-- 收款码上传 -->
        <view class="form-item">
          <MultiImageUploader
            :images.sync="paymentQrCodeImages"
            title="收款码"
            tip="请上传微信、支付宝或银行卡收款码"
            :max-count="1"
            module="settlement/qrcode"
            @upload-success="onQrCodeUpload"
          />
        </view>

        <!-- 收款人姓名 -->
        <view class="form-item">
          <text class="item-label">收款人姓名</text>
          <input 
            v-model="formData.paymentAccount" 
            placeholder="请输入收款人姓名"
            placeholder-class="placeholder"
            class="input"
          />
        </view>

        <!-- 联系电话 -->
        <view class="form-item">
          <text class="item-label">联系电话</text>
          <input 
            v-model="formData.phone" 
            type="number"
            placeholder="请输入联系电话"
            placeholder-class="placeholder"
            class="input"
          />
        </view>

        <!-- 备注 -->
        <view class="form-item">
          <text class="item-label">备注（选填）</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="如有特殊要求请填写"
            placeholder-class="placeholder"
            maxlength="200"
            class="textarea"
          />
        </view>
      </view>
    </view>

    <!-- 温馨提示 -->
    <view class="tips">
      <view class="tips-title">💡 温馨提示</view>
      <view class="tips-item">• 请确保收款信息准确无误，错误信息可能导致结算失败</view>
      <view class="tips-item">• 结算申请提交后，平台将在1-3个工作日内审核</view>
      <view class="tips-item">• 审核通过后，款项将在5个工作日内到账</view>
      <view class="tips-item">• 如有问题，请联系客服</view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">
        提交申请
      </button>
    </view>
  </view>
</template>

<script>
import { getPickupOrderDetail, applySettlement } from '@/api/pickup'
import MultiImageUploader from '@/components/MultiImageUploader.vue'

export default {
  components: {
    MultiImageUploader
  },
  data() {
    return {
      orderId: '',
      orderInfo: {},
      paymentMethods: ['微信', '支付宝', '银行卡'],
      paymentMethodIndex: 0,
      paymentQrCodeImages: [],
      formData: {
        paymentMethod: '微信',
        paymentQrCode: '',
        paymentAccount: '',
        phone: '',
        remark: ''
      }
    }
  },
  onLoad(options) {
    this.orderId = options.orderId || ''
    if (this.orderId) {
      this.loadOrderInfo()
    }
  },
  methods: {
    // 加载订单信息
    async loadOrderInfo() {
      try {
        uni.showLoading({ title: '加载中...' })
        const orderDetail = await getPickupOrderDetail(this.orderId)
        this.orderInfo = orderDetail
        uni.hideLoading()
      } catch (error) {
        console.error('加载订单信息失败:', error)
        uni.hideLoading()
        uni.showToast({ title: '加载失败', icon: 'none' })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    // 收款方式选择
    onPaymentMethodChange(e) {
      this.paymentMethodIndex = e.detail.value
      this.formData.paymentMethod = this.paymentMethods[e.detail.value]
    },

    // 收款码上传成功
    onQrCodeUpload(data) {
      //console.log('收款码上传成功:', data)
      // 将图片URL保存到表单数据
      if (this.paymentQrCodeImages.length > 0) {
        this.formData.paymentQrCode = this.paymentQrCodeImages[0]
      }
    },

    // 校验表单
    validateForm() {
      if (!this.formData.paymentQrCode || this.paymentQrCodeImages.length === 0) {
        uni.showToast({ title: '请上传收款码', icon: 'none' })
        return false
      }
      if (!this.formData.paymentAccount) {
        uni.showToast({ title: '请输入收款人姓名', icon: 'none' })
        return false
      }
      if (!this.formData.phone) {
        uni.showToast({ title: '请输入联系电话', icon: 'none' })
        return false
      }
      const phoneReg = /^1[3-9]\d{9}$/
      if (!phoneReg.test(this.formData.phone)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' })
        return false
      }
      return true
    },

    // 提交申请
    async handleSubmit() {
      // 确保收款码URL已更新到表单数据
      if (this.paymentQrCodeImages.length > 0) {
        this.formData.paymentQrCode = this.paymentQrCodeImages[0]
      }
      
      if (!this.validateForm()) return

      uni.showModal({
        title: '确认提交',
        content: `确认申请结算 ¥${this.orderInfo.riderEarning} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '提交中...' })
              await applySettlement(this.orderId, this.formData)
              uni.hideLoading()
              
              uni.showToast({ title: '申请成功', icon: 'success' })
              
              // 跳转到结算记录页面
              setTimeout(() => {
                uni.redirectTo({
                  url: '/pages/settlement/records'
                })
              }, 1500)
            } catch (error) {
              console.error('申请结算失败:', error)
              uni.hideLoading()
              uni.showToast({ title: error.msg || '申请失败', icon: 'none' })
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.apply-settlement {
  min-height: 100vh;
  background: #F5F5F5;
  padding: 24rpx;
  padding-bottom: 160rpx;
}

.section {
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

/* 订单信息卡片 */
.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  font-size: 26rpx;
  color: #999;
}

.info-row .value {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

/* 收益明细卡片 */
.earning-card {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  border-radius: 16rpx;
  padding: 32rpx;
}

.fee-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.fee-row.deduction .label,
.fee-row.deduction .value {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
}

.fee-row.total {
  margin-bottom: 0;
}

.fee-row.total .label {
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
}

.fee-row.total .value {
  font-size: 40rpx;
  color: #fff;
  font-weight: bold;
}

.fee-row .label,
.fee-row .value {
  color: #fff;
  font-size: 26rpx;
}

/* 退款相关样式 */
.fee-row.refund .value {
  color: #ff6b6b;
}

.fee-row.compensation .value {
  color: #4ecdc4;
}

.divider {
  height: 1rpx;
  background: rgba(255, 255, 255, 0.3);
  margin: 16rpx 0;
}

/* 抽成规则提示 */
.rate-tip {
  background: linear-gradient(135deg, #fff9e6 0%, #fff3cc 100%);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-top: 16rpx;
  display: flex;
  gap: 16rpx;
  align-items: flex-start;
}

.rate-tip .tip-icon {
  font-size: 40rpx;
  line-height: 1;
}

.rate-tip .tip-content {
  flex: 1;
}

.rate-tip .tip-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #f57c00;
  margin-bottom: 8rpx;
}

.rate-tip .tip-desc {
  font-size: 24rpx;
  color: #ff9800;
  line-height: 1.6;
}

/* 表单卡片 */
.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.form-item {
  margin-bottom: 24rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.item-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #F8F9FA;
  padding: 24rpx;
  border-radius: 8rpx;
}

.picker text {
  font-size: 28rpx;
  color: #333;
}

.picker .arrow {
  font-size: 40rpx;
  color: #999;
}

.input,
.textarea {
  width: 100%;
  background: #F8F9FA;
  padding: 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.textarea {
  height: 120rpx;
}

.placeholder {
  color: #999;
}

/* 温馨提示 */
.tips {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
}

.tips-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #f57c00;
  margin-bottom: 16rpx;
}

.tips-item {
  font-size: 24rpx;
  color: #f57c00;
  line-height: 1.8;
  margin-bottom: 8rpx;
}

.tips-item:last-child {
  margin-bottom: 0;
}

/* 底部按钮 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
}
</style>
